//
// 下载排班记录 2017/5/31
//
//



#import "DlHrScheduling.h"
#import "Networking.h"
#import "InitDbTable.h"
#import "UserDefault.h"
#import <TMCache.h>

@implementation DlHrScheduling

-(instancetype)init{
    
    NSString *url = AppServiceConfig.GetServiceUrl;
    self.downloadUrl  = [NSString stringWithFormat:@"%@/%@?userid=%@&empid=%@&menuid=%@&token=%@",url,@"GetScheduling",UserDefault.getUserInfo.USER_ID,UserDefault.getUserInfo.EMP_ID,[[TMCache sharedCache] objectForKey:@"MENUID"], [[TMCache sharedCache] objectForKey:@"deviceToken"]];
    
    NSLog(@"%@", self.downloadUrl);
    return self;
}

-(void) startDownload:(void(^)())callback{
    NSLog(@"开始 下载排班记录");
    
    [Networking receiveDataWithURLString:self.downloadUrl method:@"GET" body:nil Block:^(NSData *tempData) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:tempData options:NSJSONReadingMutableContainers error:nil];
        InitDbTable* initdb = [[InitDbTable alloc]init];
        
        
        Boolean flag =  [[dic valueForKey:@"flag"] boolValue];
        NSString *msg = (NSString*)[dic objectForKey: @"msg"];
        
        if(! flag ){
            
            NSLog(@"%@",msg);
            
            return;
        }
        
        NSDictionary *data = [dic objectForKey: @"data"];
        
        NSDictionary *scd_records = [data objectForKey: @"scd_records"];
        NSDictionary *scd_people = [data objectForKey: @"people"];
        NSDictionary *scd_group = [data objectForKey: @"group"];
        
        NSMutableArray *arrScdDept = [[NSMutableArray alloc]init];
        NSMutableArray *arrScdPeople = [[NSMutableArray alloc]init];
        NSMutableArray *arrScdGroup = [[NSMutableArray alloc]init];
        
        NSLog(@"下载成功");
        NSLog(@"共%lu条排班记录数据",(unsigned long)[scd_records count]);
        NSLog(@"共%lu条护理单元成员记录数据",(unsigned long)[scd_people count]);
        NSLog(@"共%lu条护理单元记录数据",(unsigned long)[scd_group count]);
        
        for (NSDictionary *diction in scd_records) {
            Model_Hr_Scheduling *model =[[Model_Hr_Scheduling alloc]initWithDictionary:diction];
            [arrScdDept addObject:model];
        }

        for (NSDictionary *diction in scd_people) {
            Model_Hr_Scheduling_Dept *model =[[Model_Hr_Scheduling_Dept alloc]initWithDictionary:diction];
            [arrScdPeople addObject:model];
        }
        
        for (NSDictionary *diction in scd_group) {
            Model_Hr_Atd_Scd_Group *model =[[Model_Hr_Atd_Scd_Group alloc]initWithDictionary:diction];
            [arrScdGroup addObject:model];
        }
        
        NSLog(@"正在清除原有排班记录数据");
        [initdb deleteHrScheduliing];
        
        
        NSLog(@"正在写入排班记录数据");
        [initdb insertHrScheduling:arrScdDept scdGroup:arrScdGroup schPeople:arrScdPeople];
        
        if(callback){
            callback();
        }
        
        NSLog(@"完成 下载排班记录");
        
    }];
    
}


@end
